package main

import (
	"gogo"
)

// 模拟用户验证函数
func validateUser(username, password string) bool {
	// 使用安全比较防止时序攻击
	return gogo.SecureCompare(username, "admin") && gogo.SecureCompare(password, "password")
}

// 自定义权限验证函数
func customAuth(ctx *gogo.HTTPContext) bool {
	// 检查请求头中的API Key
	// 通过原始的Request对象获取Header
	authHeader := ctx.GetRequest().Header.Get("X-API-Key")
	if authHeader != "" && authHeader == "secret-key" {
		return true
	}
	
	// 未通过验证，返回401
	ctx.WriteHeaderStatus(401)
	ctx.WriteString("Unauthorized: Invalid API Key\n")
	return false
}

func main() {
	// 注册一个公开的路由
	gogo.GET("/", func(ctx *gogo.HTTPContext) {
		ctx.WriteString("Hello, Public World! This is a public endpoint.\n")
	})
	
	// 示例1: 使用Basic Auth保护的路由
	gogo.GET_PRE("/basic-auth", gogo.BasicAuth(validateUser, "Please enter your username and password"))
	gogo.GET("/basic-auth", func(ctx *gogo.HTTPContext) {
		ctx.WriteString("Hello, Basic Auth World! You have been authenticated with Basic Auth.\n")
	})
	
	// 示例2: 使用自定义API Key验证保护的路由
	gogo.GET_PRE("/api", customAuth)
	gogo.GET("/api/data", func(ctx *gogo.HTTPContext) {
		ctx.WriteJSON(map[string]interface{}{
			"message": "This is protected data",
			"data":    []int{1, 2, 3, 4, 5},
		})
	})
	
	// 示例3: 保护一组路由 (所有以/admin开头的路由)
	gogo.GET_PRE("/admin", func(ctx *gogo.HTTPContext) bool {
		// 简单的用户验证 - 实际应用中应该更复杂
		// 通过GetString获取查询参数
		user := ctx.GetString("user")
		if user == "admin" {
			return true
		}
		
		ctx.WriteHeaderStatus(403)
		ctx.WriteString("Forbidden: Only admin users allowed\n")
		return false
	})
	
	gogo.GET("/admin/dashboard", func(ctx *gogo.HTTPContext) {
		ctx.WriteString("Welcome to the Admin Dashboard!\n")
	})
	
	gogo.GET("/admin/users", func(ctx *gogo.HTTPContext) {
		ctx.WriteJSON([]string{"user1", "user2", "user3"})
	})
	
	// 404 页面
	gogo.STATUS(404, func(ctx *gogo.HTTPContext) {
		ctx.WriteHeaderStatus(404)
		ctx.WriteString("Page Not Found!\n")
	})

	// 启动HTTP服务
	gogo.StartHTTP(3009)
}
